package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.time.DateFormatUtils;

import com.geepi.base.DBUtil;

public class UpdateDBServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	/**
	 * Constructor of the object.
	 */
	public UpdateDBServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = (String)request.getParameter("method");
		if(method==null) {
			PrintWriter out = response.getWriter();
			out.println("invalid request!");
		} else if(method.equals("insert")) {
			Update(request, response);
		} else if(method.equals("delete")) {
			Delete(request, response);
		} else if(method.equals("register")) {
//			Register(request, response);
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {				
		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	
	/*
	 * function 
	 */
	protected void Update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// get parameters
		String title = new String(request.getParameter("title").getBytes("ISO-8859-1"),"utf-8") ;
		String detailInfo = new String(request.getParameter("detailInfo").getBytes("ISO-8859-1"),"utf-8") ;
		String source = new String(request.getParameter("source").getBytes("ISO-8859-1"),"utf-8") ;
		String author = new String(request.getParameter("author").getBytes("ISO-8859-1"),"utf-8") ;
		String thumbUrl = new String(request.getParameter("thumb").getBytes("ISO-8859-1"),"utf-8") ;
		String detailImages = new String(request.getParameter("detailImages").getBytes("ISO-8859-1"),"utf-8") ;
		int type = 1;
		int status = -1;
		String message = "";
		JSONObject jsonObject = null;
		String querySql = "select max(id) from resource;";
			
		DBUtil dbUtil = new DBUtil();
		boolean isOpen = dbUtil.open();
		if (isOpen == false) {
			status = 102;
			message = "数据库打开失败";
		} else {
			ResultSet resultSetCount = dbUtil.query(querySql);
			try {
				while (resultSetCount.next()) {
					int MaxId = resultSetCount.getInt(1);
					MaxId ++;
					Date currentTime = new Date();  
				    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTime);

					String updateSql = String.format("insert into resource (id, title, createtime, author, detailInfo) values ('%d', '%s', '%s', '%s', '%s');",
							MaxId, title, time, author, detailInfo);
				    System.out.println("inert sql:" + updateSql);	


					boolean isInsert = dbUtil.update(updateSql);
					if (isInsert) {
						status = 0;
						message = "更新成功";
					} else {
						status = 103;
						message = "更新失败";
					}
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				status = 104;
				message = e.getMessage();
			}
		}
		
		Map<String, Object> tempParamsMap = new HashMap<String, Object>();
		tempParamsMap.put("status", status);
		tempParamsMap.put("msg", message);
		jsonObject = JSONObject.fromObject(tempParamsMap);
		
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
	}

	protected void Delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// get parameters
		String id = new String(request.getParameter("id").getBytes("ISO-8859-1"),"utf-8") ;
		int resourceId = Integer.parseInt(id);
		int type = 1;
		int status = -1;
		String message = "";
		JSONObject jsonObject = null;
		
		DBUtil dbUtil = new DBUtil();
		boolean isOpen = dbUtil.open();
		if (isOpen == false) {
			status = 102;
			message = "数据库打开失败";
		} else {
			String updateSql = "delete from resource where id = " + resourceId +";";
			boolean isInsert = dbUtil.update(updateSql);
			if (isInsert) {
				status = 0;
				message = "删除记录成功";
			} else {
				status = 103;
				message = "更新失败";
			}
		}
		
		Map<String, Object> tempParamsMap = new HashMap<String, Object>();
		tempParamsMap.put("status", status);
		tempParamsMap.put("msg", message);
		jsonObject = JSONObject.fromObject(tempParamsMap);
		
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
	}
}
